﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Microtalk.Data;
using Microtalk.Models;
using Microtalk.ViewModels;


namespace Microtalk.Controllers
{
    public class MessagesController : Controller
    {
        private MicrotalkContext db = new MicrotalkContext();

        // GET: Messages


        //自动将匿名用户转向到登录页面的支持
        // [AuthorizePlus]
        public ActionResult Index(int id )
        {
            if(Session["username"] == null)
            {
                return RedirectToAction("login/", "users");

            }
            else
            {

                var cuuentUser = db.Users.Where(x => x.Id == id).SingleOrDefault();

              
                var userList = db.Users.ToList();
  
                var msgList = db.Messages.ToList();
  
                var comList = db.Comments.ToList();

                //定义一个存放所有首页消息模型的集合
                var msgViewModelList = new List<MessageViewModel>();

                //将所有的信息转换为视图需要的模型
                foreach (var msg in msgList)
                {
                  
                    var cmgViewModelList = new List<CommentViewModel>();
                   
                    var currentMsgComments = comList.Where(x => x.MsgId == msg.Id).ToList();

                    //遍历所有的评论,并将其转换为视图需要的模型
                    foreach (var cmg in currentMsgComments)
                    {
                
                        var fromUser = userList.Where(x => x.Id == cmg.FromUserId).FirstOrDefault();
           
                        var m = msgList.Where(x => x.Id == cmg.MsgId).FirstOrDefault();
       
                        var toUser = userList.Where(x => x.Id == m.FromUserId).FirstOrDefault();

                        cmgViewModelList.Add(new CommentViewModel
                        {
                            FromUserName = fromUser.UserName,
                            ToUserName = toUser.UserName,
                            Content = cmg.Content
                        });
                    }

                    // 将消息转换为消息的视图模型
                    msgViewModelList.Add(new MessageViewModel
                    {
                        Id = msg.Id,
                        Content = msg.Content,
                        Comments = cmgViewModelList
                    });

                }

                var vm = new SayViewModel
                {
                    UserName = cuuentUser.UserName,
                    Messages = msgViewModelList
                };

                return View(vm);
            }

        }



        // GET: Messages/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // GET: Messages/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Messages/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,FromUserId,Content,CreateAt,UpdateAt,Version,Remarks")] Messages messages)
        {
            if (ModelState.IsValid)
            {
                db.Messages.Add(messages);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(messages);
        }

        // GET: Messages/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // POST: Messages/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,FromUserId,Content,CreateAt,UpdateAt,Version,Remarks")] Messages messages)
        {
            if (ModelState.IsValid)
            {
                db.Entry(messages).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(messages);
        }

        // GET: Messages/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // POST: Messages/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Messages messages = db.Messages.Find(id);
            db.Messages.Remove(messages);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
